from app import db
from app.models import EtfFund
from .base import BaseCollector
from datetime import datetime

class ETFCollector(BaseCollector):
    def __init__(self):
        super().__init__('etf')
        self.base_url = 'http://www.etf.group/data'
        
    def collect_all(self):
        """采集所有ETF数据"""
        try:
            # 采集全部列表
            all_data = self.fetch_data(f'{self.base_url}/api1.php?page=1&limit=9999')
            self._save_funds(all_data['rows']['item'])
            
            # 采集今日热点
            hot_data = self.fetch_data(f'{self.base_url}/api1_hot.php?page=1&limit=9999')
            self._save_funds(hot_data['rows']['item'])
            
            # 采集最近上市
            new_data = self.fetch_data(f'{self.base_url}/api1_new.php?page=1&limit=9999')
            self._save_funds(new_data['rows']['item'])
            
            self.log_success(self.base_url, len(all_data['rows']['item']))
            return True
        except Exception as e:
            self.log_error(self.base_url, str(e))
            return False

    def _save_funds(self, items):
        """保存基金数据"""
        for item in items:
            # 查找现有记录，没有则创建新的
            fund = EtfFund.query.filter_by(code=item['code']).first()
            if not fund:
                fund = EtfFund()
            
            # 更新字段
            for key, value in item.items():
                if hasattr(fund, key):
                    setattr(fund, key, value)
            
            fund.updated_at = datetime.utcnow()
            db.session.add(fund)
        
        db.session.commit()